import os

from dotenv import load_dotenv
from flask import Flask
from flask_cors import CORS

from app.config import config, basedir
from app.errors import register_error_handlers
from app.extensions import db, migrate
from app.routes.routes import register_routes


def create_app(config_name='default'):
    """应用工厂函数"""

    if config_name not in config:
        config_name = 'default'

    app = Flask(__name__)

    # 加载配置
    app.config.from_object(config[config_name])

    # 配置 CORS
    configure_cors(app)

    # 初始化扩展
    db.init_app(app)
    migrate.init_app(app, db)

    # 注册蓝图
    from app.routes.string_util_api import bp as api_bp
    app.register_blueprint(api_bp)

    register_routes(app)

    # 注册错误处理
    register_error_handlers(app)

    # 加载环境变量
    load_dotenv()

    return app


def configure_cors(app):
    """配置 CORS 支持容器化部署"""

    # 从环境变量获取允许的域名
    allowed_origins = os.environ.get('ALLOWED_ORIGINS', '').split(',')

    # 默认的域名列表（包含容器域名）
    default_origins = [
        'http://localhost:4173',
        'http://localhost:5173',
        'http://127.0.0.1:5173',
        'http://frontend:3000',  # Docker 开发环境
        'http://frontend:80',  # Docker 生产环境
        'http://localhost:80',  # 本地生产预览
    ]

    # 合并域名列表
    if allowed_origins and allowed_origins[0]:
        origins = allowed_origins + default_origins
    else:
        origins = default_origins

    # 去重和清理
    origins = list(set([origin.strip() for origin in origins if origin.strip()]))

    print(f"🔧 CORS 允许的域名: {origins}")

    # 配置 CORS
    CORS(app,
         resources={
             r"/api/*": {
                 "origins": origins,
                 "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
                 "allow_headers": ["Content-Type", "Authorization", "X-Requested-With"],
                 "supports_credentials": True,
                 "max_age": 600
             }
         })